<?php

/* 聊天室代码片段一，实现功能：创建socket资源并监听端口 */
function WebSocket($address, $port)
{
        $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
        socket_bind($server, $address, $port);
        socket_listen($server);
        $this->e('server start      : ' . date('Y-m-d H:i:s'));
        $this->e('listening on      : ' . $address . ' port ' . $port);
        return $server;
}

/* 聊天室代码片段二，实现功能：启动服务器端程序，并接收前端的登录，聊天等请求，并返回聊天信息给聊天室的用户 */
function run()
{
        $this->e('server is running...');
        while (true) {
            $changes = $this->sockets;
            $write = null;
            $except = NULL;
            socket_select($changes, $write, $except, NULL);     //
            foreach ($changes as $sock) {
                if ($sock == $this->master) {                   //查找到当前的客户端
                    $client = socket_accept($this->master);
                    $this->e('已经接受socket连接: ' . $this->master);
                    $this->sockets[] = $client;
                    $this->users[] = array(
                        'socket' => $client,
                        'hasHandShake' => false,
                    );
                } else {
                    $len = socket_recv($sock, $buffer, 2048, 0);
                    if ($len == 0) {
                        //$this->e("socket_read() failed reason: " . $len . "\n");
                        $this->e("socket read failed !");
                    }
                    $k = $this->search($sock);
                    if ($len < 7) {                         //如果$len的长度小于7，那么关闭这个客户端的链接
                        $name = $this->users[$k]['username'];
                        $this->close($sock);
                        $this->send2($name, $k);
                        continue;
                    }
                    if (!$this->users[$k]['hasHandShake']) {      //尚未握手，先进行握手
                        $this->handShake($k, $buffer);
                        //parse_str($buffer,$g);
                        //$this->users[$k]['username']  = $g['username'];
                    } else {                              //已经握手，开始双工通信
                        $buffer = $this->uncode($buffer);
                        $this->send($k, $buffer);
                    }
                }
            }

        }

}
